/**
 * Created by WT-SUN on 2017/4/12.
 */
$(function () {
    monitorPointTb();
    monitorTb();
    queryDepartmentTree();
    $('#btn_point_clear').on("click", function () {
        $('#queryFormPoint').form('reset');
    });
    $('#monitorTb_remove').on("click", function () {
        monitorTbRemove();
    });
    $('#monitorTb_save').on("click", function () {
        monitorTbSave();
    });
    $('#btn_clear').on("click", function () {
        $('#querySerForm').form('reset');
    });
});

function monitorPointTb() {
    $('#pointTb').datagrid({
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        toolbar: '#toolbar',
        fit: false,
        height: 300,
        url: ROOT_PATH + '/occupationalHealth/monPoint/pointTable.shtml',
        queryParams:{
            sort:'addTime',
            order:'desc'
        },
        onSelect:function (index, row) {
            debugger
            var lastIndex= $('#monitorTb').datagrid('getRowIndex', row.id+row.factorId);
            if(lastIndex>-1){
                layer.alert("本条数据已存在！");
                return;
            }
            $('#monitorTb').datagrid('appendRow',{
                pointId: row.id,
                monitorPoint1: row.monitorPoint,
                factorName1: row.factorName,
                factorUnit1:row.factorUnit,
                pointFacId:row.id+row.factorId,
                factorId:row.factorId
            });
        },
        columns: [[
            {
                field: 'id',
                checkbox: true
            },
            {field: 'monitorPoint', title: '监测点名称', width: 100, sortable: true},
            {field: 'factorName', title: '监测项目', width: 100, sortable: true},
            {field: 'factorUnit', title: '计量单位', width: 100},
            {field: 'typeName', title: '监测项目类型', width: 100},
            {field: 'companyName', title: '单位名称', width: 100},
            {field: 'userName', title: '登记人', width: 100, sortable: true},
            {field: 'deptName', title: '登记部门', width: 100}
        ]]
    });
}
var editIndex = undefined;
var endEditing= function endEditing(){
    if (editIndex == undefined){return true}
    if ($('#monitorTb').datagrid('validateRow', editIndex)){
        $('#monitorTb').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function monitorTb() {
    var isMonitorData=[{id:'0',text:'是',selected:true},{id:'1',text:'否'}];
    $('#monitorTb').datagrid({
        fitColumns: true,
        idField: 'pointId',
       // pagination: true,
        rownumbers: true,
        sortOrder: true,
        fit: false,
        height: 300,
        columns: [[
            {
                field: 'pointId', title: 'pointId', hidden:true,width: 20
            },
            {
                field: 'factorId', title: 'factorId', hidden:true,width: 20
            },
            {
                field: 'pointFacId', title: 'pointFacId', hidden:true,width: 20
            },
            {field: 'monitorPoint1', title: '监测点名称', width: 100},
            {field: 'factorName1', title: '监测项目', width: 100},
            {field: 'factorUnit1', title: '计量单位', width: 100},
            {field: 'monitorCompanyId', hidden:true,title: '单位Id', width: 100,editor: {
                type: 'textbox',
                options:{
                    //required:true
                }
            }},

            {field: 'monitorResult', title: '监测结果', width: 100, editor: { type: 'numberbox', options: { required: true,min:0,precision:2 } }},
            {field: 'maxNum', title: '最大值', width: 80, editor: { type: 'numberbox'  }},
            {field: 'minNum', title: '最小值', width: 80,  editor: { type: 'numberbox' }},
            {field: 'isMonitor', title: '是否自行监测', width: 100,
                formatter: function (value, row, index){
                    return row.isMonitor=='0'?'是':(row.isMonitor=='1'?'否':'');
                },
                editor: {
                type: 'combobox',
                options: {
                    data: isMonitorData,
                    editable:false,
                    valueField: 'id',
                    textField: 'text',
                    required: true,
                    onSelect: function (record) {
                        var name = record.text;
                        var ed = $("#monitorTb").datagrid('getEditor', { index: editIndex, field: 'monitorCompanyName' });
                        if(ed==null){
                            return;
                        }
                        if (name == "否") {
                            $(ed.target).textbox({
                                required: true
                            });
                        } else {
                            $(ed.target).textbox({
                                required: false
                            });
                        }
                    }
                }
            }},
            {field: 'monitorCompanyName', title: '监测单位', width: 100,
                editor: {
                    type: 'textbox',
                    options:{
                        iconWidth: 20,
                        editable:false,
                        icons: [{
                            iconCls: 'icon-add',
                            handler: function(e){
                                openSerViceTb();
                            }
                        },{
                            iconCls: 'icon-remove',
                            handler: function(e){
                                $(e.data.target).textbox('clear');
                                var edId = $("#monitorTb").datagrid('getEditor', { index: editIndex, field: 'monitorCompanyId' });
                                $(edId.target).textbox('setValue', '').textbox('setText', '');
                            }
                        }]
                    }
                }},
            {field: 'isOverproof', title: '是否超标', width: 100,
                formatter: function (value, row, index){
                    return row.isOverproof=='0'?'是':(row.isMonitor=='1'?'否':'');
                },
                editor: {
                    type: 'combobox',
                    options: {
                        data: isMonitorData,
                        valueField: 'id',
                        editable:false,
                        textField: 'text',
                        required: true
                    }
                }},
            {field: 'cbNum', title: '超标倍数', width: 100, editor: { type: 'numberbox', options: { min:0,precision:2 } }},
            {field: 'cxNum', title: '超限倍数', width: 100, editor: { type: 'numberbox', options: { min:0,precision:2 } }},
            {field: 'monitorDate', title: '监测日期', width: 100,editor: {type: 'datebox', options: {required: true,editable:false, validateOnBlur: true}}}
        ]],
        onClickRow:function (index, row) {
            if (editIndex != index){
                if (endEditing()){
                    $('#monitorTb').datagrid('selectRow', index).datagrid('beginEdit', index);

                    editIndex = index;
                } else {
                    $('#monitorTb').datagrid('selectRow', editIndex);
                }
            }

        }
    });
}
function openSerViceTb() {
    WindowManager.openLayer({
        type: 2,
        title: '选择服务机构',
        area: ['850px', '70%'],
        content: ROOT_PATH + '/occupationalHealth/hseServiceOrg/orgTb.shtml',
        callBack:function(data){
            getSelectedOrg(data);
        }
    });
}
function getSelectedOrg(data) {
    var ed = $("#monitorTb").datagrid('getEditor', { index: editIndex, field: 'monitorCompanyName' });
    var edId = $("#monitorTb").datagrid('getEditor', { index: editIndex, field: 'monitorCompanyId' });
    $(ed.target).textbox('setValue', data[0].serviceName).textbox('setText', data[0].serviceName);
    $(edId.target).textbox('setValue', data[0].id).textbox('setText', data[0].id);
}
function reLoadPointData() {
    $('#pointTb').datagrid('clearSelections');
    var queryParams = $('#queryFormPoint').serializeJson();
    queryParams["sort"] = 'addTime';
    queryParams["order"] = 'desc';
    $('#pointTb').datagrid('options').queryParams = queryParams;
    $("#pointTb").datagrid('reload', ROOT_PATH + '/occupationalHealth/monPoint/pointTable.shtml');
}
function monitorTbSave() {
    if (endEditing()){
       // $('#monitorTb').datagrid('acceptChanges');
    }
    var objArr=$('#monitorTb').datagrid('getData');
    if(objArr.total==0){
        layer.alert("请选择数据！");
        return;
    }
    for (var i=0;i<objArr.total;i++){
        var rowData=objArr.rows[i];
        if (typeof (rowData.monitorResult)=='undefined'||typeof (rowData.isMonitor)=='undefined'||typeof (rowData.monitorDate)=='undefined'){
            layer.alert("请正确填写监测数据！");
            return;
        }
        if (rowData.monitorResult==''||rowData.isMonitor==''||rowData.monitorDate==''){
            layer.alert("请正确填写监测数据！");
            return;
        }
    }
    var listTb= JSON.stringify(objArr.rows);
    $.ajax({
        url:ROOT_PATH + '/occupationalHealth/monitor/insertSelective.shtml',//提交地址
        data:listTb,
        type:"POST",
        dataType:"json",
        contentType:"application/json",
        success: function (result) {
            if (result.success) {
                layer.msg('保存成功', {
                    icon: 1,
                    time: 1000
                }, function () {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                    $.getIframeWindow().reLoadData();
                });
            }
            else {
                layer.msg('保存失败', {
                    icon: 2,
                    time: 1000
                });
            }
        }
    });
}
function monitorTbRemove() {
    if (editIndex == undefined){return}
    $('#monitorTb').datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
    editIndex = undefined;
}
/**
 * 查询部门树方法
 */
function queryDepartmentTree(){
    $.ajax({
        url:ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data:{parentId : 0},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#companyName').combotree(
                {
                    data:result,
                    require:true,
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        newData.push(data[0]);
                        return newData;
                    }
                }
            );
        }
    });
}
